<?php
/*
 * @Author: 哲学家乔布斯 <wuyangii@qq.com>
 * @Date: 2022-10-20 21:41:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-11-07 22:37:15
 * @Descripttion: 获取支付
 */

namespace app\api\controller\user\v1_0;


use EasyWeChat\Factory;
use think\Db;
class WechatPay extends Common
{
    protected $noNeedRight = ['index'];
    /**
     * @Author: 哲学家乔布斯 <wuyangii@qq.com>
     * @brief: 
     * @return 
     * @Descripttion: 首页默认接口
     */    
    public function index(){
        $order_id = request()->param('order_id');
        $order_on = "P".date('YmdHis') . rand(1000, 9999);
        (new \app\common\model\PayOrders())->insertGetId([
            'order_id' => $order_id,
            'order_on' => $order_on,
            'type' => "user",
            'pay_type' => "wechat",
        ]);
        $user = (new \app\common\model\User())->where(['id' => $this->UserInfo['id']])->find();
        $order = (new \app\common\model\UserOrders())->where(['id' => $order_id])->find();
        $this->wechat($user['openid'],$order_on,$order['money']);
    }

    protected function wechat($openid,$order_on,$money){

        $config = (new \app\common\model\AgentConfig())->where(['agent_id' => $this->agent_id])->find();
       
        $app = Factory::payment([
                'app_id'             => $config['appid'],
                'mch_id'             => $config['pay_mch_id'],
                'key'                => $config['pay_key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
                'notify_url'         => config("wechat.user.notify_url.pay"),     // 你也可以在下单时单独设置来想覆盖它
        ]);
        // $app = Factory::payment([
        //     'app_id'             => config("wechat.user.wechat.app_id"),
        //     'mch_id'             => config("wechat.user.pay.mch_id"),
        //     'key'                => config("wechat.user.pay.key"),   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
        //     'notify_url'         => config("wechat.user.notify_url.pay"),     // 你也可以在下单时单独设置来想覆盖它
        // ]);


    
        $money = $openid == "oR5eI7a0EKXiKgLoXXUSiJ6wUe40" ? 1 : $money*100;
      
        $result = $app->order->unify([
            'body' => config('wechat.title').$order_on,
            'out_trade_no' => $order_on,
            'total_fee' => $money,
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ], false);
  
        if ($result['return_code'] == "FAIL") return self::errorResult(['state' => 0, 'body' => $result['return_msg']]);
        $jssdk = $app->jssdk;
        return self::successResult("成功",$jssdk->bridgeConfig($result['prepay_id'],false));
    }
    
    public function callback($out_trade_no=''){
        $xml = file_get_contents('php://input');
        $arr = simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA);
        $xmljson= json_encode($arr);//将对象转换个JSON
        $xmlarray=json_decode($xmljson,true);//将json转换成数组
        $pay_order = (new \app\common\model\PayOrders())->where(['order_on' => $xmlarray['out_trade_no']])->find();
        $order = (new \app\common\model\UserOrders())->where(['id' => $pay_order['order_id']])->find();
        $config = (new \app\common\model\AgentConfig())->where(['agent_id' => $order['agent_id']])->find();
        $app = Factory::payment([
            'app_id'             => $config['appid'],
            'mch_id'             => $config['pay_mch_id'],
            'key'                => $config['pay_key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
            'notify_url'         => config("wechat.user.notify_url.pay"),     // 你也可以在下单时单独设置来想覆盖它
    ]);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            $out_trade_no = $message['out_trade_no'];
            $pay_order = (new \app\common\model\PayOrders())->where(['order_on' => $out_trade_no])->find();
            if($pay_order['pay_time'] > 0){
                return self::errorResult("该订单已成功支付");
            }
            Db::startTrans();
            try{
                $message = "订单创建失败,请重试";
                $process = true;
                $row = (new \app\common\model\PayOrders())->where(['id' => $pay_order['id']])->update([
                    'pay_time' => time(),
                    'state' => 1,
                ]);
                if(!$row){
                    $message = "支付订单修改失败，请重试";
                    $process = false;
                }
    
                $row = (new \app\common\model\UserOrders())->where(['id' => $pay_order['order_id']])->update([
                    'paytime' => time(),
                    'state' => 1,
                ]);
                if(!$row){
                    $message = "订单修改失败，请重试";
                    $process = false;
                }
    
                ##------------------修改商品销量 ------------------
                $goods = (new \app\common\model\UserOrdersGoods())->where(['order_id' => $pay_order['order_id']])->select();
                foreach ($goods as $key => $value) {
                    $goodss = (new \app\common\model\AgentGoodsSku())->where(['id' => $value['agent_goods_sku_id']])->find();
                    $goods = (new \app\common\model\AgentGoodsSku())->where(['id' => $value['agent_goods_sku_id']])->find();          
                    $row = (new \app\common\model\AgentGoodsSku())->where(['id' => $value['agent_goods_sku_id'],'sales' => $goodss['sales']])->update([
                        'sales' => $goodss['sales']+$value['num']
                    ]);
                    if(!$row){
                        $message = "订单修改失败,请重试增加商品销量失败";
                        $process = false;
                    }
                }
                
    
                if ($process !== false) {
                    Db::commit(); // 提交事务
                } else {
                    Db::rollback(); // 回滚事务
                }
             } catch (\Exception $e) {
                $process = false;
                $message = $e->getMessage();
                Db::rollback(); // 回滚事务
            }
            if ($process !== false) {
                echo "success"; exit;
            } else {
                echo "fail"; exit;
            }
        });
       
    }
   

}
